package nit.wave.service;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;
import nit.wave.dao.DataBaseDAO;
import nit.wave.model.Student;
import nit.wave.utils.HttpRequest;
import nit.wave.utils.SignUtil;
import nit.wave.utils.WeixinUtil;

public class JwxtService {

	public String binding(String openId, String userId, String password) {
		String result = "";
		try {
			int count = DataBaseDAO.findUserByOpenId("jwxt_user", openId);
			System.out.println(count);
			if (count == 0) {
				int countUser = DataBaseDAO.findUserByuSserId("jwxt_user", userId);
				if (countUser == 0) {
					result = this.login(userId, password);
					JSONObject node = JSONObject.fromObject(result);
					int code = node.getInt("code");
					if (code == 200) {
						try {
							if (DataBaseDAO.intsertUser("jwxt_user", new Student(openId, userId, password)))
								return "绑定成功";
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				} else {
					return "您的帐号已在其他设备绑定";
				}
			} else {
				return "您的帐号已绑定";
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	private String login(String userId, String password) {
		Map<String, String> param = new HashMap<String, String>();
		param.put("secret", WeixinUtil.JWXT_SECRET);
		param.put("userID", userId);
		param.put("userPwd", password);
		return HttpRequest.sendPost("http://nitjwxt.hiunique.com/login", param);
	}

	public String changePassword(String openId, String password) {
		String result = null;
		try {
			Student student = DataBaseDAO.getStudent("jwxt_user", openId);
			Map<String, String> param = new HashMap<String, String>();
			param.put("userID", student.getUserId());
			param.put("userPwd", student.getPassword());
			param.put("oldPwd", student.getPassword());
			param.put("newPwd", password);
			param.put("secret", SignUtil.toSHA(student.getUserId(), WeixinUtil.JWXT_SECRET));
			result = HttpRequest.sendPost("http://nitjwxt.hiunique.com/login/pwdmodify", param);
			JSONObject node = JSONObject.fromObject(result);
			int code = node.getInt("code");
			if (code == 200) {
				DataBaseDAO.updatePassword("jwxt_user", openId, password);
				return "修改成功";
			} else if (code == 202) {
				return "密码强度太弱";
			} else {
				return "密钥错误";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

}
